import re
import redis


def get_relation(measure_table_name, win_conn, path):
    '''
    获取cube量值表或视图与维度表的关系
    :param measure_table_name: 量值对应表名
    :param win_conn:远程主机连接对象
    :param path:远程文件路径
    :return: 返回当前量值与其关联维度的关系字典
    '''
    redis_conn = redis.Redis(host='127.0.0.1', port=6379, db=12)
    redis_key = "{}-{}-dsv-relation".format(win_conn.host, path)
    if not redis_conn.get(redis_key):
        # 获取文件内容
        file_names = win_conn.get_files('*.dsv.xml', path)
        content = ''
        for file_name in file_names:
            if 'dsv' in file_name:
                content = win_conn.get_file_connect(file_name, path)
        redis_conn.set(redis_key, content, ex=60 * 60 * 24)  # ex参数设置60s过期
    else:
        content = redis_conn.get(redis_key).decode('utf-8')
    redis_conn.close()
    # 表名不同bug修复
    pat = re.compile('<msdata:Relationship(.*?)msprop:Description=""/>')
    content_list = pat.findall(content.replace('\r\n', ''))
    dim_tables = []
    for item in content_list:
        # 判断item的child是否等于measure_table_name
        child_pat = re.compile('msdata:child="(.*?)" msdata:parentkey')
        child_list = child_pat.findall(item)
        for child_item in child_list:
            if measure_table_name == child_item:
                dim_pat = re.compile('msdata:parent="(.*?)"')
                dim_tables += dim_pat.findall(item.replace('\r\n', ''))

    return {measure_table_name: dim_tables}

    # 按<>匹配，找到量值名称所在<>
    # pat = re.compile('<msdata:Relationship name="{}(.*?)>'.format(measure_table_name))
    # content_list = pat.findall(content.replace('\r\n', ''))
    # # 获取对应维度表列表
    # dim_tables = []
    # for item in content_list:
    #     dim_pat = re.compile('msdata:parent="(.*?)"')
    #     dim_tables += dim_pat.findall(item.replace('\r\n', ''))
    #
    # return {measure_table_name: dim_tables}


if __name__ == '__main__':
    from app_cube.utils.connect.my_win import MyWin

    win_conn = MyWin('127.0.0.1', 'Administrator', 'zjs')
    path = r'C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Data\YWC_SSAS.0.db'
    relation = get_relation('View_Fact_Inhosp_Fee_Detail', win_conn, path)
    print(relation)
